<template>
  <van-nav-bar
    title="编辑地址"
    left-text="返回"
    left-arrow
    @click-left="goAddress"
  />

  <van-address-edit
    :area-list="areaList"
    show-set-default
    show-delete
    :address-info="AddressInfo"
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    @save="onSave"
    delete-button-text="清空"
    @delete="clearAddressInfo"
  />
</template>
<script>
import { showToast } from "vant";
import { areaList } from "@vant/area-data";
import { service } from "../api/config";
export default {
  name: "addressEdit",
  data() {
    return {
      //加载地区
      areaList,
      AddressInfo: {
        name: "",
        tel: "",
        province: "",
        city: "",
        county: "",
        addressDetail: "",
        isDefault: true,
        id: "",
        areaCode: "",
      },
    };
  },
  methods: {
    goAddress() {
      this.$router.push("/address");
    },
    onSave(value) {
      service
        .post("/wx/address/save", {
          name: value.name,
          tel: value.tel.replace(/^(\d{3})(\d{4})(\d{4})$/, "$1 $2 $3"), //字符串截取。电话格式
          province: value.province,
          city: value.city,
          county: value.county,
          addressDetail: value.addressDetail,
          isDefault: value.isDefault == true ? "true" : "false",
        })
        .then((res) => {
          console.log(res);
          if (res.data.errmsg == "成功") {
            this.isSaving == true;
            showToast("地址保存成功,2秒后跳转到地址管理");
            setTimeout(() => {
              this.$router.push("address");
            }, 2000);
          } else {
            showToast("保存失败");
          }
        });
    },
    clearAddressInfo() {
      // clearData() 方法将默认数据对象与当前数据对象进行合并，这样可以重置数据对象并清除所有数据。
      Object.assign(this.$data, this.$options.data.call(this));
    },
  },
};
</script>
